from PyQt5.QtWidgets import (
    QLabel,
    QListWidget,
    QListWidgetItem,
    QHBoxLayout,
    QVBoxLayout,
    QPushButton,
    QDialog,
)
from .utils import clear_layout

from PyQt5.QtCore import Qt


class RecorderDialog(QDialog):
    def __init__(self, recorder):
        super().__init__()
        self.setWindowTitle("Preview Change")
        self.recorder = recorder
        self.result_layout = QHBoxLayout()
        self.init_result_layout(recorder)
        clean_btn = QPushButton("clean")
        clean_btn.clicked.connect(self.clean)
        self.v_layout = QVBoxLayout()
        self.v_layout.addLayout(self.result_layout)
        self.v_layout.addWidget(clean_btn)
        self.setLayout(self.v_layout)

        # 设置对话框类型
        self.setWindowFlags(Qt.Tool)

    def init_result_layout(self, recorder):
        clear_layout(self.result_layout)
        lists = {}
        for i, (name, folder) in enumerate(recorder.mapping.items()):
            if folder not in lists:
                list_widget = QListWidget(self)
                box = QVBoxLayout()
                btn = QLabel(folder)
                list_widget.itemDoubleClicked.connect(self.remove_item)
                lists[folder] = list_widget
                box.addWidget(btn)
                box.addWidget(list_widget)
                self.result_layout.addLayout(box)
            else:
                list_widget = lists[folder]
            item = QListWidgetItem(name)
            list_widget.addItem(item)

    def remove_item(self, item):

        self.recorder.remove(item.text())

        self.init_result_layout(self.recorder)

        # for name, val in self.lists.items():
        #     if val == item.listWidget():
        #         print(name)
        #         break

    def clean(self):
        if self.recorder is not None:
            self.recorder.apply()
        else:
            print("need to preview first")
